package springmvc.web.cocktails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

import org.dhbw.cocktail.Cocktail;
import org.dhbw.cocktail.mixer.ICocktailMixer;
import org.dhbw.cocktail.mixer.MixerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Controller to view and mix a cocktail
 * @author Roland von Werden
 *
 */
@Data
public class CocktailsController implements Controller {

	/**
	 * autowirde mixerfactory to access methods to create, get and search
	 * persisted Objects
	 */
	@Autowired
	@Qualifier("cocktail_mixer_factory")
	MixerFactory mixerFactory;
	ICocktailMixer mixer;
 
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		mixer = mixerFactory.getCocktailMixer();
		// Show a specified coctail on the basis of its ID
		if (request.getParameter("id") != null) {
			// mix a cocktail with the specified ID
			if (request.getParameter("mix") != null) {
				try {
					return mixCocktail(Long.valueOf(request.getParameter("id")),
							Integer.valueOf(request.getParameter("quantity")));
				} catch (NumberFormatException e) {
				}
			} else {
				try {
					// return single cocktail
					return processSingleCocktail(Long.valueOf(request
							.getParameter("id")));
				} catch (NumberFormatException e) {
				}
			}
		}
		// return a list of all cocktails available
		return processCocktails();
	}

	private ModelAndView processSingleCocktail(long id) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("view_cocktail", true);
		Cocktail cocktail = mixer.getCocktailById(id);
		mav.addObject("cocktail", cocktail);
		mav.addObject("ingredients", cocktail.getIngredientsUsed());
		return mav;
	}

	private ModelAndView processCocktails() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("select_cocktail", true);
		mav.addObject("cocktails", mixer.getAllCocktails());
		return mav;
	}

	private ModelAndView mixCocktail(long id, int amount) {
		ModelAndView mav = processSingleCocktail(id);
		Cocktail cck = (Cocktail) mav.getModel().get("cocktail");
		mav.addObject("cocktail_mixed", mixer.mixCocktail(cck, amount));
		mav.addObject("amount", amount);
		return mav;
	}

}
